<!--vue模板   closeOnClickModal 设置为false ，点击遮罩时不会关闭dialog ，否则会关闭-->
<template>
  <el-dialog
    v-model="visible"
    :closeOnClickModal="false"
    width="35%"
    :title="title"
    @close="close"
  >
    <el-form label-width="120px">
      <el-form-item label="角色名称">
        <el-input v-model="role.name" />
      </el-form-item>

      <el-form-item label="权限">
        <AuthTree ref="authtree" :roleId="role.id"></AuthTree>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="role.note" type="textarea" resize="none" :rows="4" />
      </el-form-item>
    </el-form>

    <div style="text-align: center">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>

<!--vue 组件选项定义-->
<script>
import { Plus } from "@element-plus/icons-vue";
import AuthTree from "./AuthTree.vue";
export default {
  data() {
    return {
      role: {
        name: "",
        note: "",
      },
    };
  },
  computed: {
    title() {
      if (this.role.id) {
        return "修改角色";
      }
      return "添加角色";
    },
  },
  components: {
    Plus,
    AuthTree,
  },
  emits: ["update:visible", "refreshData"],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },

  methods: {
    init(data) {
      if (data == undefined) {
        //说明用户执行的添加
        this.role = {
          name: "",
          note: "",
        };
      } else {
        //修改
        this.role = data;
      }
      //手动调用authtree查询菜单树
        this.$refs.authtree.queryTree();
    },

    save() {
      let tmp = this.$refs.authtree.getCheckedKey();
      //将权限节点值复制到this.role上
      Object.assign(this.role, tmp);
      let promise;
      if (this.role.id) {
        //id存在 说明是修改
        promise = this.$http.put("/api/role/update", this.role);
      } else {
        promise = this.$http.post("/api/role/save", this.role);
      }
      promise.then((res) => {
        if (res.code == 200) {
          this.$message.success("保存成功");
          //关闭弹框
          this.close();

          //通知父组件刷新数据
          this.$emit("refreshData");
        }
      });
    },

    close() {
      this.$emit("update:visible", false);
    },
  },
};
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.hid {
  display: none;
}
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}
</style>
